<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>
<script>
var jsTestIsAsync = true;

description("Tests that document.defaultView on a detached document doesn't crash.");

var cachedWindow;
var cachedDocument;
var testFrameUnloaded = false;

// DRT dumps out the number of unload handlers associated with a document once it loads.
// Unfortunately, load order is not guaranteed, so wait until the first frame has finished loading
// before setting up the rest of the test.
function setupTest()
{
    var frame2 = document.createElement('iframe');
    frame2.srcdoc = '<script>window.onunload=function() { window.top.finishTest(); };</scr' + 'ipt>';
    frame2.onload = runTest;
    document.getElementById('frames').appendChild(frame2);
}

function runTest()
{
    var i = document.getElementById("testFrame");
    // Make sure DOMWindow doesn't get GCed and clear Document's pointer back to it.
    cachedWindow = i.contentWindow;
    cachedDocument = i.contentDocument;
    // This test is structured to catch a document.defaultView crash when all of the following are true:
    // 1. Document's pointer back to DOMWindow has not yet been cleared by DOMWindow destruction.
    // 2. DOMWindow's pointer back to its Frame has not yet been cleared by Frame destruction.
    // 3. The frame is already detached.
    // One way to satisfy this condition is to test the value of document.defaultView when removing
    // a DOM node that contains multiple subframes, since ChildFrameDisconnector keeps a ref to the
    // affected HTMLFrameOwnerElements (and consequently the Frame) on the stack.
    var frameContainer = document.getElementById("frames");
    frameContainer.parentNode.removeChild(frameContainer);
}

function finishTest()
{
    shouldBeTrue("testFrameUnloaded");
    shouldBeNull("cachedDocument.defaultView");
    finishJSTest();
}
</script>
<body onload="setupTest()">
  <div id="frames">
    <iframe id="testFrame" srcdoc="<script>window.onunload=function() { window.top.testFrameUnloaded = true; };</script>"></iframe>
  </div>
</body>
